package com.scwatch.core.web.back;

import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.orm.RowSide;
import com.scwatch.common.util.Dates;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.Context;
import com.scwatch.core.support.Siteable;
import com.scwatch.ext.domain.LiveBroadcast;
import com.scwatch.ext.service.LiveBroadcastService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.scwatch.core.constant.Constants.*;

@Controller
@RequestMapping("/core/live_broadcast_room")
public class LiveBroadcastRoomController {
    private static final Logger logger = LoggerFactory.getLogger(HotWordController.class);

    @Autowired
    private SiteService siteService;

    //设置评论 限制
    @RequiresPermissions("core:live_broadcast_room:liveConfig")
    @RequestMapping("liveConfig.do")
    public String liveConfig(HttpServletRequest request,
                             org.springframework.ui.Model modelMap) {
        String stat = request.getParameter("stat");
        Site site = Context.getCurrentSite();
        String infoid = request.getParameter("infoid");
        SiteComment siteComment = new SiteComment(site.getCustoms());
        modelMap.addAttribute("bean", siteComment);
        modelMap.addAttribute("stat", stat);
        modelMap.addAttribute("infoid", infoid);//房间ID
        return "core/live_broadcast_room/comment_live_conf";
    }

    //保存设置
    //设置评论 限制
    @RequiresPermissions("core:live_broadcast_room:liveConfigUpata")
    @RequestMapping("liveConfigUpata.do")
    public String liveConfigUpata(SiteComment bean, HttpServletRequest request,
                                  RedirectAttributes ra) {
        String infoid = request.getParameter("infoid");
        Site site = Context.getCurrentSite();
        String stat = request.getParameter("stat");
//		String ftype =request.getParameter("ftype");
        siteService.updateConf(site, bean);
        logService.operation("opr.liveConfigUpata.edit", site.getName(),
                null, site.getId(), request);
        logger.info("update Comment config.");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addAttribute("id", infoid);
        ra.addAttribute("stat", stat);
        return "redirect:list.do";
    }


    /**
     * @title : 主要用于直播间 - 聊天室 - 定时刷新
     * @serialData 2017年9月6日10:19:41
     **/
    @RequestMapping("liveRoomList.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:live_broadcast_room:liveRoomList")
    public @ResponseBody
    String liveRoomList(@PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
                        HttpServletRequest request) {
        int Siteid = Context.getCurrentSiteId();
        Map<String, String[]> params = new HashMap<String, String[]>();
        params.put("EQ_fid", request.getParameterValues("fid"));
        params.put("EQ_ftype", request.getParameterValues("ftype"));
        Page<Comment> comments = commentService.findAll(Siteid, params, pageable,false);

        List<JSONObject> list = new ArrayList<JSONObject>();
        for (Comment comment : comments.getContent()) {
            JSONObject json = new JSONObject();
            User user = comment.getCreator();
            if (user != null) {
                String userName = user.getUsername();
                if (StringUtils.isNotBlank(userName)) {
                    json.put("userName", userName);
                }
            }
            Integer status = comment.getStatus();
            if (status != null) json.put("status", status);
            String txt = comment.getText();
            if (StringUtils.isNotBlank(txt)) json.put("text", txt);
            Integer score = comment.getScore();
            if (score != null) json.put("score", score);
            String ip = comment.getIp();
            if (StringUtils.isNotBlank(ip)) json.put("ip", ip);
            String country = comment.getCountry();
            if (StringUtils.isNotBlank(country)) json.put("country", country);
            String area = comment.getArea();
            if (StringUtils.isNotBlank(area)) json.put("area", area);
            Date creationDate = comment.getCreationDate();
            if (creationDate != null) json.put("creationDate", Dates.formatDate(creationDate, "yyyy-MM-dd HH:mm:ss"));
            Date auditDate = comment.getAuditDate();
            if (auditDate != null) json.put("auditDate", Dates.formatDate(auditDate, "yyyy-MM-dd HH:mm:ss"));
            list.add(json);
        }
        JSONObject json = new JSONObject();
        json.put("data", list);
        json.put("totalPages", comments.getTotalPages());
        json.put("totalElements", comments.getTotalElements());
        String value = json.toJSONString();
        return value;
    }

    @RequestMapping("list.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:live_broadcast_room:list")
    public String list(
            @PageableDefault(sort = "creationDate", direction = Sort.Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap, Integer id, Integer roombeanId) {

        int Siteid = Context.getCurrentSiteId();
        if (id == null) {
            id = roombeanId;
        }
        String stat = request.getParameter("stat");
        String tab = request.getParameter("tab");

        String roomId = request.getParameter("roomId");
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        LiveBroadcastRoom bean = null;
        if (roomId != null) {
            bean = service.get(Integer.valueOf(roomId));
        }
        modelMap.addAttribute("roombean", bean);
        List<LiveBroadcastRoom> pagedList = service.getRoomListByParam(id);

        modelMap.addAttribute("pagedList1", pagedList);
        modelMap.addAttribute("liveid", id);
        modelMap.addAttribute("stat", stat);
        modelMap.addAttribute("roomId", roomId);
        params.put("EQ_fid", new String[]{id.toString()});
        params.put("EQ_ftype", new String[]{"Live"});
        Page<Comment> comments = commentService.findAll(Siteid, params, pageable,false);
        modelMap.addAttribute("pagedList", comments);

        LiveBroadcast liveBroadcast = liveBroadcastService.get(id);

        modelMap.addAttribute("stat", liveBroadcast.getStatus());
        modelMap.addAttribute("liveurl", liveBroadcast.getTaddress());
        modelMap.addAttribute("lookbaclurl", liveBroadcast.getfLookBack());
        modelMap.addAttribute("roomId", id);

        modelMap.addAttribute("tab", tab);
        String oprt = request.getParameter("oprt");
        if (StringUtils.isNotEmpty(oprt)) {
            modelMap.addAttribute(OPRT, oprt);
        }
        return "core/live_broadcast_room/liveroom_list";
    }

    @RequestMapping("create.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:live_broadcast_room:create")
    public String create(Integer id, org.springframework.ui.Model modelMap) {
        if (id != null) {
            LiveBroadcastRoom bean = service.get(id);
            modelMap.addAttribute("bean", bean);
        }
        modelMap.addAttribute(OPRT, CREATE);
        return "core/live_broadcast_room/liveroom_list";
    }


    @RequestMapping("edit.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:live_broadcast_room:edit")
    public String edit(
            Integer id,
            Integer position,
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap, RedirectAttributes ra) {
        LiveBroadcastRoom bean = service.get(id);
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);

        String stat = request.getParameter("stat");
        ra.addAttribute("roomId", id);
        ra.addAttribute("stat", stat);
        ra.addAttribute("id", bean.getLiveId());
        ra.addAttribute("oprt", "edit");
        return "redirect:list.do";
    }

    @RequiresPermissions("ext:live_broadcast_room:update")
    @RequestMapping("update.do")
    public String update(@ModelAttribute("roombean") LiveBroadcastRoom bean, Integer[] id,
                         String[] title, Integer status, Integer subscribe, Integer review, HttpServletRequest request,
                         String redirect, RedirectAttributes ra) {
        if (bean.getContent() != null || bean.getVideo() != null) {
            Site site = Context.getCurrentSite();
            User user = Context.getCurrentUser();
            if(bean.getTime()==null){
                bean.setTime(new Date());
            }
            bean = service.update(bean);
            JSONObject json = new JSONObject();
            try {//推送直播间
                LiveJush(site, user, bean);
            } catch (Exception e) {
            }
        }
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            return "redirect:edit.do";
        }
    }

    @RequestMapping("save.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:live_broadcast_room:save")
    public String save(LiveBroadcastRoom bean, String redirect,
                       HttpServletRequest request, RedirectAttributes ra) {
        if (bean.getContent() != null) {
            Site site = Context.getCurrentSite();
            User user = Context.getCurrentUser();
            if(bean.getTime()==null){
                bean.setTime(new Date());
            }
            bean = service.save(bean);
            if (bean != null) {
                try {//推送直播间
                    LiveJush(site, user, bean);
                } catch (Exception e) {
                }
            }
        }
        String stat = request.getParameter("stat");
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        ra.addAttribute("roomId", bean.getId());
        ra.addAttribute("stat", stat);
        ra.addAttribute("id", bean.getLiveId());
        ra.addAttribute("tab", "room");
        return "redirect:list.do";
    }

    //直播间 推送
    private void LiveJush(Site site, User user, LiveBroadcastRoom bean) {
        JSONObject json = new JSONObject();
        try {//推送直播间
            /*--------------[ 直播 推送需要的字段 ]--------------*/
            JSONObject beanJson = new JSONObject();
            try {
                String content = bean.getContent();
                String image = bean.getImage();
                if (image != null) {
                    String[] images = image.split(",");
                    String coverImage = images[0];
                    beanJson.put("coverImage", coverImage);//视频封面图
                    beanJson.put("dynamicImage", images);//图片
                }
                Integer beanId = bean.getId();
                beanJson.put("dynamicId", beanId);//直播间信息的ID
                beanJson.put("dynamicText", content == null ? "" : content);//内容
                beanJson.put("dynamicVideo", bean.getVideo() == null ? "" : bean.getVideo());//视频地址
                beanJson.put("pubTime", bean.getTime() == null ? "" : Dates.formatDate(bean.getTime(), "yyyy-MM-dd HH:mm:ss"));//时间
            } catch (Exception e) {
            }
            JSONObject extr = new JSONObject();
            extr.put("pushType", 1);//0正常、1推送直播间动态、2聊天室
            extr.put("data", bean);
                  /*-----[封装 评论数据]------*/
            json.put("title", "");//通知内容标题
            json.put("msgTile", "");//消息内容标题
            json.put("content", "直播间");//消息内容
            json.put("isOpen", true);//是否静默
            json.put("groupTag", bean.getLiveId() == null ? "" : bean.getLiveId().toString());//分组直播间
            json.put("extrasparam", extr);//扩展字段
            try {
                jpushService.JpushIosOrAndroid(site, user, json);
            } catch (Exception e) {
            }
        } catch (Exception e) {
        }
    }


    @RequiresPermissions("ext:live_broadcast_room:delete")
    @RequestMapping("delete.do")
    public String delete(Integer[] ids, HttpServletRequest request,
                         RedirectAttributes ra) {
        LiveBroadcastRoom[] beans = service.delete(ids);
        for (LiveBroadcastRoom bean : beans) {
            logService.operation("opr.LiveBroadcastRoom.delete", bean.getContent(), null,
                    bean.getId(), request);
            logger.info("delete LiveBroadcastRoom, title={}.", bean.getContent());
            ra.addAttribute("id", bean.getLiveId());
        }
        ra.addAttribute("tab", "room");
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }

    private void validateIds(Integer[] ids, Integer siteId) {
        for (Integer id : ids) {
            Backends.validateDataInSite((Siteable) service.get(id), siteId);
        }
    }


    @Autowired
    private LiveBroadcastRoomService service;
    @Autowired
    private OperationLogService logService;

    @Autowired
    private LiveBroadcastService liveBroadcastService;


    @Autowired
    private CommentService commentService;

    /*----------------------------------------------[ 聊天室 编辑 和审核  方法 ]--------------------------------------------*/
    @ModelAttribute("bean")
    public Comment preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? commentService.get(oid) : null;
    }

    //更新聊天室数据
    @RequiresPermissions("core:comment:LiveCommentupdate")
    @RequestMapping("LiveCommentupdate.do")
    public String LiveCommentupdate(@ModelAttribute("bean") Comment bean,
                                    Integer position, String redirect, HttpServletRequest request,
                                    Integer liveId, String stat,
                                    RedirectAttributes ra) {
        Backends.validateDataInSite(bean, Context.getCurrentSiteId());
        commentService.update(bean);

        logger.info("update Comment, id={}.", bean.getId());
        logService.operation("opr.comment.edit",
                StringUtils.substring(bean.getText(), 0, 150), null,
                bean.getId(), request);
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);

        ra.addAttribute("stat", stat);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            ra.addAttribute("tab", request.getParameter("tab"));
            ra.addAttribute("id", liveId);
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            ra.addAttribute("liveId", liveId);
            return "redirect:commentedit.do";
        }
    }

    //编辑某一条聊天数据
    @RequiresPermissions("core:live_broadcast_room:commentedit")
    @RequestMapping("commentedit.do")
    public String commentedit(
            Integer id,
            Integer position,
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable, Integer liveId, String stat,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        Comment bean = commentService.get(id);
        Backends.validateDataInSite(bean, site.getId());
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        RowSide<Comment> side = commentService.findSide(site.getId(), params, bean,
                position, pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);

        modelMap.addAttribute("liveId", liveId);
        modelMap.addAttribute("stat", stat);
        modelMap.addAttribute("tab", "Liveroom");
        modelMap.addAttribute(OPRT, EDIT);
        return "core/live_broadcast_room/comment_live_form";
    }


    //删除某一条聊天室 记录
    @RequiresPermissions("core:comment:commentdelete")
    @RequestMapping("comment_delete.do")
    public String comment_delete(Integer[] ids, HttpServletRequest request, Integer liveId, String stat,
                                 RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
//        validateIds(ids, site.getId());
        Comment[] beans = commentService.delete(ids);
        for (Comment bean : beans) {
            logService.operation("opr.comment.comment_delete",
                    StringUtils.substring(bean.getText(), 0, 150), null,
                    bean.getId(), request);
            logger.info("delete Comment, id={}.", bean.getId());
        }
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("id", liveId);
        ra.addAttribute("stat", stat);
        ra.addAttribute("tab", request.getParameter("tab"));
        return "redirect:list.do";
    }

    @Autowired
    private JpushService jpushService;

    //审核
    @RequiresPermissions("core:live_broadcast_room:commentaudit")
    @RequestMapping("commentaudit.do")
    public String commentaudit(Integer[] ids, HttpServletRequest request, Integer liveId, String stat,
                               RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
//        validateIds(ids, site.getId());
        Comment[] beans = commentService.audit(ids);
        //评论数据封装
        List<JSONObject> jsonJush = new ArrayList<JSONObject>();
        for (Comment bean : beans) {
            JSONObject json = new JSONObject();
            try {
                User user1 = bean.getCreator();
                if (user1 != null) {
                    Integer id = user1.getId();
                    String nickName = user1.getNickname();
                    String iph =user1.getUsername();
                    String avatar = user1.getAvatarSmall();
                    json.put("userId", id == null ? "" : id);
                    json.put("avatar", avatar == null ? "" : avatar);
                    json.put("nickName", nickName == null ? iph==null?"匿名":((iph.length() > 10) ? iph.substring(0,4)+"*******":iph) : nickName);
                }
                json.put("commentId", bean.getId());
                json.put("comment", bean.getText());//bean.getTime() == null ? "" : Dates.formatDate(bean.getTime(), "yyyy-MM-dd HH:mm:ss")
                json.put("pubTime", bean.getCreationDate() == null ? "" : Dates.formatDate( bean.getCreationDate(), "yyyy-MM-dd HH:mm:ss"));
            } finally {
                jsonJush.add(json);
            }
            logService.operation("opr.comment.audit",
                    StringUtils.substring(bean.getText(), 0, 150), null,
                    bean.getId(), request);
            logger.info("audit Comment, id={}.", bean.getId());
        }
        JSONObject json = new JSONObject();
        try {
                /*-----[封装 评论数据]------*/
            JSONObject extr = new JSONObject();
            extr.put("pushType", 2);//0正常、1推送直播间动态、2聊天室
            extr.put("data", jsonJush);

            json.put("title", "");//通知内容标题
            json.put("msgTile", "");//消息内容标题
            json.put("content", "直播聊天室");//消息内容
            json.put("isOpen", true);//是否静默
            json.put("groupTag", liveId.toString());//分组信息
            json.put("extrasparam", extr);//扩展字段
            try {
                jpushService.JpushIosOrAndroid(site, user, json);
            } catch (Exception e) {
            }
        } catch (Exception e) {
            logger.info("推送异常数据为：{} 异常信息：{}", json.toJSONString(), e.getSuppressed());
        } finally {
            ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
            ra.addAttribute("id", liveId);
            ra.addAttribute("stat", stat);
            ra.addAttribute("tab", "Liveroom");
            return "redirect:list.do";
        }
    }

    //未审核
    @RequiresPermissions("core:live_broadcast_room:commentanti_audit")
    @RequestMapping("commentanti_audit.do")
    public String commentanti_audit(Integer[] ids, HttpServletRequest request, Integer liveId, String stat,
                                    RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
//        validateIds(ids, site.getId());
        Comment[] beans = commentService.unaudit(ids);
        for (Comment bean : beans) {
            logService.operation("opr.comment.antiAudit",
                    StringUtils.substring(bean.getText(), 0, 150), null,
                    bean.getId(), request);
            logger.info("unaudit Comment, id={}.", bean.getId());
        }
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("id", liveId);
        ra.addAttribute("stat", stat);
        ra.addAttribute("tab", "Liveroom");
        return "redirect:list.do";
    }

    //删除当前直播，直播间全部内容
    @RequiresPermissions("core:live_broadcast_room:delAllRoom")
    @RequestMapping("delAllRoom.do")
    public String delAllRoom(HttpServletRequest request,
                         RedirectAttributes ra,Integer liveId) {
        LiveBroadcast liveBroadcast=liveBroadcastService.get(liveId);
        try {
            if(liveBroadcast!=null){
                //指定 99999条数据
                List<LiveBroadcastRoom> roomlist=service.getRoomListByParam(liveId);
                List<Integer> roomIdList=new ArrayList<>();
                for(LiveBroadcastRoom room:roomlist){
                    roomIdList.add(room.getId());
                }
                Integer[] roomIds=new Integer[roomIdList.size()];
                roomIds=roomIdList.toArray(roomIds);
                service.delete(roomIds);
            }
        } catch (Exception e) {
            ra.addAttribute("id",liveId);
            ra.addAttribute("tab", "room");
            ra.addFlashAttribute(MESSAGE,OPERATION_FAILURE);
            return "redirect:list.do";
        }
        logService.operation("opr.LiveBroadcastRoom.delAllRoom",liveBroadcast.getTitle(), null,
                liveId, request);
        logger.info("delAllRoom LiveBroadcastRoom, liveId={}.",liveId);
        ra.addAttribute("id",liveId);
        ra.addAttribute("tab", "room");
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }


    //删除当前直播，聊天室全部内容
    @RequiresPermissions("core:comment:delAllComment")
    @RequestMapping("delAllComment.do")
    public String delAllComment(HttpServletRequest request, Integer liveId, String stat,
                                 RedirectAttributes ra) {
        LiveBroadcast liveBroadcast=liveBroadcastService.get(liveId);
        try {
            if(liveBroadcast!=null){
                commentService.deleteByFtypeAndFid("Live",liveId);
            }
        } catch (Exception e) {
            ra.addFlashAttribute(MESSAGE, OPERATION_FAILURE);
            ra.addAttribute("id", liveId);
            ra.addAttribute("stat", stat);
            ra.addAttribute("tab","Liveroom");
        }
        logService.operation("opr.comment.delAllComment",liveBroadcast.getTitle(), null, liveId, request);
        logger.info("delAllComment liveId={}.",liveId);
        ra.addFlashAttribute(MESSAGE, OPERATION_SUCCESS);
        ra.addAttribute("id", liveId);
        ra.addAttribute("stat", stat);
        ra.addAttribute("tab","Liveroom");
        return "redirect:list.do";
    }
}
